package auth

import (
	"strings"

	"github.com/gin-gonic/gin"

	"go_user_manager/pkg/adapters/agin"
)

func JWTAuthMiddleware(auth *JWTAuth) gin.HandlerFunc {
	return func(c *gin.Context) {
		authorization := c.GetHeader("Authorization")
		if authorization == "" {
			agin.WriteResponse(c, agin.ResponseData{Message: "Authorization header is required"}, nil)
			c.Abort()
			return
		}

		parts := strings.SplitN(authorization, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			agin.WriteResponse(c, agin.ResponseData{Message: "Authorization header format must be Bearer {token}"}, nil)
			c.Abort()
			return
		}

		claims, err := auth.ParseToken(parts[1])
		if err != nil {
			agin.WriteResponse(c, agin.ResponseData{Message: "Invalid or expired token"}, nil)
			c.Abort()
			return
		}

		c.Set("user_id", claims.UserID)
		c.Set("user_name", claims.UserName)
		c.Next()
	}
}
